package com.wwcom.darteagle.data;

import java.util.ArrayList;
import java.util.List;

import com.wwcom.darteagle.model.DartStats;
import com.wwcom.darteagle.model.MatchInfo;
import com.wwcom.darteagle.model.MatchPlayer;
import com.wwcom.darteagle.model.Player;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

public class DartStatsObject extends DataObject {
    private static final String TABLE_NAME = "DARTSTATS";
    private static final String TABLE_CREATE =
            "CREATE TABLE " + TABLE_NAME + " (" +
            "DARTSTATS_ID integer primary key autoincrement," +
            "PLAYER_ID integer," + 
            "MATCH_ID integer," + 
            "DARTSTATS_LEG integer," + 
            "DARTSTATS_SET integer," + 
            "DARTSTATS_TYPE integer," + 
            "DARTSTATS_DATA text" + 
            ");";

    
    public DartStatsObject(SQLiteDatabase database) {
    	super(database);
    }
    
	static public String createSQL() {
		return TABLE_CREATE;
	}

	static public String deleteSQL() {
		return "DROP TABLE IF EXISTS "+TABLE_NAME;
	}	
	
    static public String upgradeSQL(int oldVersion, int newVersion) {
		String sql= "";
		for (int i = oldVersion; i < newVersion; ++i) {
			int nextVersion = i + 1;
			switch (nextVersion) {
			// version 1 to version 2
			case 2:
				break;
			// version 2 to version 3
			case 3:
				break;
			// version 3 to version 4
			case 4:
				// added TABLE
				sql += TABLE_CREATE;
				break;
			}
		}
		if (sql.equals(""))
			sql= null;
		return sql;    	
    }
    
    public DartStats get(MatchInfo mi, Player p, int setInd, int legInd) {
    	if (p.getId() == -1) { //player ID is not set
    		throw new RuntimeException("DartStatsObject::get - player ID not set");
    	}
    	
    	Cursor cursor = database.query(TABLE_NAME, 
    			new String[] {"DARTSTATS_ID","MATCH_ID","PLAYER_ID","DARTSTATS_LEG",
    			"DARTSTATS_SET","DARTSTATS_TYPE","DARTSTATS_DATA"}, 
    			"MATCH_ID="+mi.getId()+" and PLAYER_ID="+p.getId()+" and DARTSTATS_LEG="+legInd+
    			" and DARTSTATS_SET="+setInd, null, null, null, null);
    	//set match player
    	MatchPlayer matchPlayer= null;
    	for (MatchPlayer mp : mi.getMatchPlayers()) {
    		if (mp.getPlayer().getName().equals(p.getName())) {
    			matchPlayer= mp;
    			break;
    		}
    	}
    	DartStats ds= new DartStats(mi,matchPlayer,setInd,legInd);
    	while (cursor.moveToNext()) {    		
    		int type= cursor.getInt(cursor.getColumnIndex("DARTSTATS_TYPE"));
    		String val= cursor.getString(cursor.getColumnIndex("DARTSTATS_DATA"));
    		String[] stats;
    		switch (type) {
    		case DartStats.AVERAGE:
                stats= TextUtils.split(val, ",");
                ds.setAverage(Float.parseFloat(stats[0]),Integer.parseInt(stats[1]));                
                break;
    		case DartStats.FIRST9AVERAGE:
                stats= TextUtils.split(val, ",");
                ds.setFirst9Average(Float.parseFloat(stats[0]),Integer.parseInt(stats[1]));                
                break;
    		case DartStats.HIGHESTSCORE:
                ds.setHighestScore(Integer.parseInt(val));                
                break;
    		case DartStats.PLUS60:
                ds.setPlus60(Integer.parseInt(val));                
                break;
    		case DartStats.PLUS100:
                ds.setPlus100(Integer.parseInt(val));                
                break;
    		case DartStats.PLUS140:
                ds.setPlus140(Integer.parseInt(val));                
                break;
    		case DartStats.PLUS180:
                ds.setPlus180(Integer.parseInt(val));                
                break;
    		case DartStats.DOUBLES:
                stats= TextUtils.split(val, ",");
                ds.setDoublePercentage(Integer.parseInt(stats[0]),Integer.parseInt(stats[1]));                
                break;
    		case DartStats.CHECKOUTS:
                stats= TextUtils.split(val, ",");
                ds.setCheckoutPercentage(Integer.parseInt(stats[0]),Integer.parseInt(stats[1]));                
                break;
    		case DartStats.HIGHESTCHECKOUT:
                ds.setHighestCheckout(Integer.parseInt(val));                
                break;
    		case DartStats.PLUS50CHECKOUT:
                ds.setPlus50Checkout(Integer.parseInt(val));                
                break;
    		case DartStats.PLUS100CHECKOUT:
                ds.setPlus100Checkout(Integer.parseInt(val));                
                break;                                
    		case DartStats.ACCURACY20:
                stats= TextUtils.split(val, ",");
                ds.setAccuracy20Rating(Float.parseFloat(stats[0])*Integer.parseInt(stats[1]),Integer.parseInt(stats[1]));                
                break;                                
    		case DartStats.ACCURACY19:
                stats= TextUtils.split(val, ",");
                ds.setAccuracy19Rating(Float.parseFloat(stats[0])*Integer.parseInt(stats[1]),Integer.parseInt(stats[1]));                
                break;                                
    		case DartStats.PERCENTAGE20:
                stats= TextUtils.split(val, ",");
                ds.setAccuracy20Percentage(Integer.parseInt(stats[0]),Integer.parseInt(stats[1]));                
                break;                                
    		case DartStats.PERCENTAGE19:
                stats= TextUtils.split(val, ",");
                ds.setAccuracy19Percentage(Integer.parseInt(stats[0]),Integer.parseInt(stats[1]));                
                break;                                
    		case DartStats.INDIVIDUALDOUBLES:
                stats= TextUtils.split(val, ",");
                for (int i=0; i<21; i++) {
                	ds.setIndividualDoublesPercentage(i,Integer.parseInt(stats[i*2]),
                			Integer.parseInt(stats[i*2+1]));
                }
                break;                                
    		}
    	}
    	return ds;
    }
    
    public List<DartStats> get(Player p) {
    	MatchInfoObject mio= new MatchInfoObject(database);
    	List<MatchInfo> matchInfoList= mio.getPlayerMatchInfos(p.getName());
    	List<DartStats> dsList= new ArrayList<DartStats>(matchInfoList.size());
    	for (MatchInfo mi : matchInfoList) {
    		dsList.add(get(mi,p,-1,-1));
    	}
    	return dsList;
    }    
    
    public void insert(DartStats ds)
    {
    	Log.d("DartStatsObject","Insert - MatchId: "+ds.getMatchInfo().getId()+
    			", PlayerId: "+ds.getMatchPlayer().getPlayer().getId()+
    			", Type: "+DartStats.AVERAGE+", legInd: "+ds.getLegInd()+
    			", setInd: "+ds.getSetInd()+
    			", data: "+ds.getAverageTotal()+","+ds.getAverageNDarts());
    	//Average
        ContentValues contentValues = new ContentValues();
        contentValues.put("MATCH_ID", ds.getMatchInfo().getId());        
        contentValues.put("PLAYER_ID", ds.getMatchPlayer().getPlayer().getId());
        contentValues.put("DARTSTATS_LEG", ds.getLegInd());
        contentValues.put("DARTSTATS_SET", ds.getSetInd());
        contentValues.put("DARTSTATS_TYPE", DartStats.AVERAGE);
        contentValues.put("DARTSTATS_DATA", ds.getAverageTotal()+","+ds.getAverageNDarts());        
        database.insert(TABLE_NAME, null, contentValues);

        //First9Average
        contentValues.put("DARTSTATS_TYPE", DartStats.FIRST9AVERAGE);
        contentValues.put("DARTSTATS_DATA", ds.getFirst9AverageTotal()+","+ds.getFirst9AverageNDarts());        
        database.insert(TABLE_NAME, null, contentValues);

        //Highest score
        contentValues.put("DARTSTATS_TYPE", DartStats.HIGHESTSCORE);
        contentValues.put("DARTSTATS_DATA", ds.getHighestScore());        
        database.insert(TABLE_NAME, null, contentValues);
        
        //60+
        contentValues.put("DARTSTATS_TYPE", DartStats.PLUS60);
        contentValues.put("DARTSTATS_DATA", ds.getPlus60());        
        database.insert(TABLE_NAME, null, contentValues);
        
        //100+
        contentValues.put("DARTSTATS_TYPE", DartStats.PLUS100);
        contentValues.put("DARTSTATS_DATA", ds.getPlus100());        
        database.insert(TABLE_NAME, null, contentValues);

        //140+
        contentValues.put("DARTSTATS_TYPE", DartStats.PLUS140);
        contentValues.put("DARTSTATS_DATA", ds.getPlus140());        
        database.insert(TABLE_NAME, null, contentValues);
    
        //180s
        contentValues.put("DARTSTATS_TYPE", DartStats.PLUS180);
        contentValues.put("DARTSTATS_DATA", ds.getPlus180());        
        database.insert(TABLE_NAME, null, contentValues);

        //Double %
        contentValues.put("DARTSTATS_TYPE", DartStats.DOUBLES);
        contentValues.put("DARTSTATS_DATA", ds.getDoubleAttempts()+","+ds.getDoubleSuccesses());        
        database.insert(TABLE_NAME, null, contentValues);

        //Checkout %
        contentValues.put("DARTSTATS_TYPE", DartStats.CHECKOUTS);
        contentValues.put("DARTSTATS_DATA", ds.getCheckoutAttempts()+","+ds.getCheckoutSuccesses());        
        database.insert(TABLE_NAME, null, contentValues);
        
        //Highest Checkout
        contentValues.put("DARTSTATS_TYPE", DartStats.HIGHESTCHECKOUT);
        contentValues.put("DARTSTATS_DATA", ds.getHighestCheckout());        
        database.insert(TABLE_NAME, null, contentValues);

        //50+ Checkouts
        contentValues.put("DARTSTATS_TYPE", DartStats.PLUS50CHECKOUT);
        contentValues.put("DARTSTATS_DATA", ds.getPlus50Checkout());        
        database.insert(TABLE_NAME, null, contentValues);

        //100+ Checkouts
        contentValues.put("DARTSTATS_TYPE", DartStats.PLUS100CHECKOUT);
        contentValues.put("DARTSTATS_DATA", ds.getPlus100Checkout());        
        database.insert(TABLE_NAME, null, contentValues);
        
        //Accuracy 20
        contentValues.put("DARTSTATS_TYPE", DartStats.ACCURACY20);
        contentValues.put("DARTSTATS_DATA", (ds.getAccuracy20Rating()/100)+","+ds.getAccuracy20Attempts());        
        database.insert(TABLE_NAME, null, contentValues);

        //Accuracy 19
        contentValues.put("DARTSTATS_TYPE", DartStats.ACCURACY19);
        contentValues.put("DARTSTATS_DATA", (ds.getAccuracy19Rating()/100)+","+ds.getAccuracy19Attempts());        
        database.insert(TABLE_NAME, null, contentValues);
        
        //Percentage 20
        contentValues.put("DARTSTATS_TYPE", DartStats.PERCENTAGE20);
        contentValues.put("DARTSTATS_DATA", ds.getAccuracy20Attempts()+","+ds.getAccuracy20Successes());        
        database.insert(TABLE_NAME, null, contentValues);
        
        //Percentage 19
        contentValues.put("DARTSTATS_TYPE", DartStats.PERCENTAGE19);
        contentValues.put("DARTSTATS_DATA", ds.getAccuracy19Attempts()+","+ds.getAccuracy19Successes());        
        database.insert(TABLE_NAME, null, contentValues);
        
        //Individual Doubles
        contentValues.put("DARTSTATS_TYPE", DartStats.INDIVIDUALDOUBLES);
        String data= "";
        for (int i= 0; i<21; i++) {
        	data+= ds.getIndividualDoubleAttempts(i)+","+ds.getIndividualDoubleSuccesses(i);
        	if (i<20) 
        		data+= ",";
        }
        contentValues.put("DARTSTATS_DATA", data);        
        database.insert(TABLE_NAME, null, contentValues);
        
    }    
    
    public void deleteAll(long matchId) {
    	database.delete(TABLE_NAME, "MATCH_ID=?", new String[] { Long.toString(matchId) } );
    }    
       
    
}
